package com.kevin.service.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kevin.service.entity.SysOrg;
import com.kevin.service.mapper.SysOrgMapper;
import com.kevin.service.service.SysOrgService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 机构管理
 *
 * @author 阿沐 babamu@126.com
 */
@Service
@AllArgsConstructor
public class SysOrgServiceImpl extends ServiceImpl<SysOrgMapper, SysOrg> implements SysOrgService {

    @Override
    public List<Long> getSubOrgIdList(Long id) {
        // 所有机构的id、pid列表
        List<SysOrg> orgList = list();

        // 递归查询所有子机构ID列表
        List<Long> subIdList = new ArrayList<>();
        getTree(id, orgList, subIdList);

        // 本机构也添加进去
        subIdList.add(id);

        return subIdList;
    }

    private void getTree(Long id, List<SysOrg> orgList, List<Long> subIdList) {
        for(SysOrg org : orgList){
            if (org.getPid().equals(id)){
                getTree(org.getId(), orgList, subIdList);

                subIdList.add(org.getId());
            }
        }
    }

    /**
     * 列表
     *
     * @return {@code List<SysOrg>}
     */
    @Override
    public List<SysOrg> list() {
        return baseMapper.list();
    }
}
